package codeGenerator;

import java.util.Iterator;

import model.ClasseElement;
import model.MetaModel;
import codeGenerator.visitor.GetterSetterPrintingVisitor;
import codeGenerator.visitor.MemberPrintingVisitor;

public class JavaCodeGenerator {

	protected MemberPrintingVisitor mMemberVisitor = new MemberPrintingVisitor();

	protected GetterSetterPrintingVisitor mGetterSetterVisitor = new GetterSetterPrintingVisitor();

	protected MetaModel mMetaModel;

	public void generateCodeFor(MetaModel aMetaModel) {
		this.mMetaModel = aMetaModel;

		// Création de chacune des classes.
		Iterator<ClasseElement> classIt = aMetaModel.getClasses().iterator();
		while (classIt.hasNext()) {
			this.generateClasse(classIt.next());
		}
	}

	public void generateClasse(ClasseElement aClasseElement) {

		String className = aClasseElement.getName();

		// Création du fileWriter
		JavaFileWriter fileWriter = new JavaFileWriter("src/generated/" + className);
		this.setCurrentFileWriter(fileWriter);

		// add Classe package
		fileWriter.println("package " + aClasseElement.getPackage() + ";");
		fileWriter.printNewLine();

		// Add ClasseDefinition (with attributes)
		aClasseElement.accept(mMemberVisitor);

		// Add attributes getter and setter
		aClasseElement.accept(mGetterSetterVisitor);

		fileWriter.println("}");
		fileWriter.closeStream();
	}

	protected void setCurrentFileWriter(JavaFileWriter aJavaFileWriter) {
		this.mMemberVisitor.setWriter(aJavaFileWriter);
		this.mGetterSetterVisitor.setWriter(aJavaFileWriter);
	}
}